package com.aaa.sys.service.impl;

import com.aaa.sys.entity.Dept;
import com.aaa.sys.mapper.DeptMapper;
import com.aaa.sys.service.DeptService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author ykq
 * @since 2020-11-26
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    @Override
    public List<Dept> findDeptTree() {
        //查询所有的部门信息
        List<Dept> depts = this.baseMapper.selectList(null);
        //声明一个父节点集合
        List<Dept> root=new ArrayList<>();
        for(Dept parent:depts){
            if(parent.getPid()==0){
                root.add(parent);
            }
        }
        //遍历一级菜单，找到它下面所有的子菜单
        for(Dept parent:root){
            parent.setChildren(findChild(parent.getDeptId(),depts));
        }
        return root;
    }

    /**
     *
     * @param page 当前页码
     * @param limit 每页显示的条数
     * @param dept 查询条件
     * @return
     */
    @Override
    public Page<Dept> searchDept(Integer page, Integer limit, Dept dept) {
        Page<Dept> pageinfo=new Page<>(page,limit); //封装一个分页类
        String fullName = dept.getFullName();
        QueryWrapper<Dept> queryWrapper=new QueryWrapper<>(); //封装了一个查询条件类
        if(StringUtils.isNotEmpty(fullName)){
            queryWrapper.like("full_Name",fullName);
        }
        if(dept.getDeptId()!=null){
            //查询所有的部门。
            List<Dept> depts = this.baseMapper.selectList(null);
            List<Dept> child = findChild(dept.getDeptId(), depts);//根据当前id查询该id下的所有子菜单
            List<Long> list = child.stream().map(item -> item.getDeptId()).collect(Collectors.toList());
            list.add(dept.getDeptId());
            queryWrapper.in("dept_id",list);
        }
        this.baseMapper.selectPage(pageinfo,queryWrapper);
        return pageinfo;
    }

    /**
     * 查询子菜单
     * @param pid
     * @param depts
     * @return
     */
    private List<Dept> findChild(Long pid,List<Dept> depts){
        List<Dept> children=new ArrayList<>(); //存放子菜单
        for(Dept dept:depts){
            if(dept.getPid()==pid){
                children.add(dept);
            }
        }
        //遍历children
        for(Dept child:children){
            child.setChildren(findChild(child.getDeptId(),depts));
        }
        return children;
    }
}
